package id.ac.amikom.amikomsocial;

import java.util.ArrayList;
import java.util.HashMap;

import com.markupartist.android.widget.PullToRefreshListView;
import com.markupartist.android.widget.PullToRefreshListView.OnRefreshListener;

import id.ac.amikom.libs.AdemDBHelper;
import id.ac.amikom.libs.AdemServiceHelper;
import id.ac.amikom.libs.CustomAdapter;
import android.app.Dialog;
import android.app.ListActivity;
import android.content.Intent;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.Toast;

public class AdemMateriActivity extends ListActivity {

	private AdemDBHelper db = null;
	private ListAdapter adapter;
	private Integer[] pid;

	private class GetDataTask extends AsyncTask<Void, Void, Void> {

		@Override
		protected Void doInBackground(Void... params) {

			Cursor c = db.getLogin();
			if (c.getCount() > 0) {

				AdemServiceHelper srv = new AdemServiceHelper(
						AdemMateriActivity.this);
				if (srv.checkMateriService())
					srv.getMateriService();
			}
			return null;

		}

		@Override
		protected void onPostExecute(Void result) {

			Cursor c = db.getLogin();
			if (c.getCount() > 0)
				setList();
			else
				Toast.makeText(
						AdemMateriActivity.this,
						"Refresh Materi Failed, Please Login from Menu Setting",
						Toast.LENGTH_LONG).show();

			((PullToRefreshListView) getListView()).onRefreshComplete();
			super.onPostExecute(result);
		}
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.adem_list);

		((PullToRefreshListView) getListView())
				.setOnRefreshListener(new OnRefreshListener() {
					public void onRefresh() {
						new GetDataTask().execute();
					}
				});

		db = new AdemDBHelper(this);

		Cursor c = db.getLogin();

		if (c.getCount() > 0)
			setList();
		else
			Toast.makeText(AdemMateriActivity.this,
					"Refresh Materi Failed, Please Login from Menu Setting",
					Toast.LENGTH_LONG).show();

		db.close();

	}

	public void setList() {
		try {

			Cursor cr = db.getMateri();
			startManagingCursor(cr);

			ArrayList<HashMap<String, Object>> newsList = new ArrayList<HashMap<String, Object>>();
			int i = 0;
			pid = new Integer[cr.getCount()];

			if (cr.moveToFirst()) {
				do {

					String[] f = cr.getString(cr.getColumnIndex("file")).split(
							"[/]");
					String t[] = f[2].split("[.]");
					String type = t[t.length - 1];

					pid[i] = Integer.parseInt(cr.getString(0));
					HashMap<String, Object> map = new HashMap<String, Object>();

					if (type.equals("doc") || type.equals("docx"))
						map.put("icon", R.drawable.i_word);
					else if (type.equals("xls") || type.equals("xlsx"))
						map.put("icon", R.drawable.i_excel);
					else if (type.equals("ppt") || type.equals("pptx"))
						map.put("icon", R.drawable.i_ppt);
					else if (type.equals("pdf"))
						map.put("icon", R.drawable.i_pdf);
					else
						map.put("icon", R.drawable.i_other);

					// Log.i("type", type);

					map.put("dosen", cr.getString(1) + "\n" + cr.getString(2));
					map.put("judul", cr.getString(3));
					newsList.add(map);
					i++;

				} while (cr.moveToNext());

			}

			adapter = new CustomAdapter(this, newsList, R.layout.adem_list_img,
					new String[] { "judul", "dosen", "icon" }, new int[] {
							R.id.list_title, R.id.list_date, R.id.list_image });

			setListAdapter(adapter);
			registerForContextMenu(getListView());
			db.close();

		} catch (Exception e) {
			Log.e("Exception found ", e.getMessage());
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.layout.adem_menu, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {

		switch (item.getItemId()) {
		case R.id.id_login:
			// new GetDataTask().execute();
			startActivity(new Intent(AdemMateriActivity.this,
					AdemLoginActivity.class));
			finish();

			return true;
		case R.id.id_setting:
			startActivity(new Intent(AdemMateriActivity.this,
					AdemSettingActivity.class));
			finish();

			return true;
		case R.id.id_about:
			Dialog dialog = new Dialog(this);
			dialog.setContentView(R.layout.adem_info);
			dialog.setTitle("Amikom Social");
			dialog.setCancelable(true);
			dialog.show();

			return true;
		default:
			return super.onOptionsItemSelected(item);
		}

	}

	@Override
	public void startManagingCursor(Cursor c) {

		if (Build.VERSION.SDK_INT < 11) {
			super.startManagingCursor(c);
		}
	}

	public void onListItemClick(ListView l, View v, int position, long id) {
		super.onListItemClick(l, v, position, id);

		int ids = pid[position - 1];
		Intent i = new Intent(AdemMateriActivity.this,
				AdemViewMateriActivity.class);
		i.putExtra("_id", "" + ids);

		startActivity(i);

	}

}
